package manage.service;

import m.common.model.util.*;
import m.common.service.Service;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.StringUtil;
import manage.model.DictionaryData;
import manage.model.DictionaryType;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DictionaryTypeService extends Service {

	public List<DictionaryType> getDictionaryTypeList(String searchText,QueryPage page,QueryOrder order) throws SQLException, MException{
		List<QueryCondition> conditionList= new ArrayList<>();
		if(!StringUtil.isSpace(searchText)){
			searchText=searchText.trim();
			String[] st=searchText.split("\\s+");
			conditionList.addAll(QueryCondition.manyLike("name", st));
			conditionList.addAll(QueryCondition.manyLike("type", st));
		}
		return ModelQueryList.getModelList(DictionaryType.class,
			new String[]{"oid","name","type"},
			page,
			QueryCondition.or(conditionList.toArray(new QueryCondition[]{})),
			order
		);
	}

	public List<DictionaryData> getDictionaryDataList() throws SQLException, MException{
		List<QueryCondition> conditionList= new ArrayList<>();
		conditionList.add(QueryCondition.eq("dictionaryType.oid","101"));
		QueryCondition queryCondition=QueryCondition.and(QueryCondition.and(conditionList.toArray(new QueryCondition[]{})));
		return ModelQueryList.getModelList(DictionaryData.class,
			new String[]{"oid","value"},
			null,
			queryCondition);
	}
	public void save(DictionaryType model) throws Exception {
		ModelCheckUtil.check(model);
		ModelCheckUtil.checkUniqueCombine(model, new String[]{"name","type"});
		if(model.getType().contains(",")){
			throw new MException(this.getClass(),"类型不能包含英文逗号");
		}else if(model.getName().contains(",")){
			throw new MException(this.getClass(),"名称不能包含英文逗号");
		}else if(!model.getType().matches("[a-zA-Z]*")) {
			throw new MException(this.getClass(), "类型只能包含大小写字母");
		}
		if(StringUtil.isSpace(model.getOid())){
			model.setOid(GenerateID.generatePrimaryKey());
			ModelUpdateUtil.insertModel(model);
		}else{
			ModelUpdateUtil.updateModel(model, "name");
		}
	}
}
